package com.mlnx.device.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mlnx.common.form.PageForm;
import com.mlnx.data.entity.BpInfo;
import com.mlnx.device.dao.mysql.BpDeviceMapper;
import com.mlnx.device.entity.BpDevice;
import com.mlnx.device.entity.Device;
import com.mlnx.device.pojo.dto.BpDeviceDto;
import com.mlnx.device.pojo.form.BpDeviceFilterForm;
import com.mlnx.device.pojo.form.BpDeviceForm;
import com.mlnx.device.service.BpDeviceService;
import com.mlnx.device.service.DeviceService;
import com.mlnx.device.service.LanyaDeviceService;
import com.mlnx.device.session.core.XmbpDeviceSession;
import com.mlnx.device.session.manager.MutilDeviceSessionManager;
import com.mlnx.device.util.SortUtil;
import com.mlnx.service.base.service.BaseService;
import com.mlnx.service.common.enums.ResponseEnum;
import com.mlnx.service.common.exception.MutilDeviceServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class BpDeviceServiceIml extends BaseService<BpDeviceMapper, BpDevice> implements BpDeviceService {
    @Autowired
    @Override
    public void setBaseMapper(BpDeviceMapper baseMapper) {
        super.setBaseMapper(baseMapper);
    }

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private MutilDeviceSessionManager sessionManager;

    @Autowired
    private LanyaDeviceService lanyaDeviceService;


    @Override
    @Transactional
    public void addBpDevice(BpDeviceForm bpDeviceForm,Integer userId) {
        Device device = new Device();
        device.setNumeration(bpDeviceForm.getNumeration());
        device.setValidTime(bpDeviceForm.getValidTime());
        device.setDeviceTypeId(bpDeviceForm.getDeviceType());
        device.setPatientId(bpDeviceForm.getPatientId() == null ? 0 : bpDeviceForm.getPatientId());
        device.setUserId(userId);
        deviceService.save(device);

        try {
            BpDevice bpDevice = new BpDevice();
            bpDevice.setId(device.getId());
            bpDevice.setMac(bpDeviceForm.getMac());
            baseMapper.insert(bpDevice);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new MutilDeviceServiceException(ResponseEnum.ServerError);
        }
    }

    @Override
    public Page<BpDeviceDto> list(PageForm pageForm, BpDeviceFilterForm bpDeviceFilterForm) {
        Page<BpDeviceDto> bpDeviceDtoPage = baseMapper.selectDeviceDtoPage(new Page<BpDeviceDto>(pageForm.getCurrent(),
                pageForm.getSize()), bpDeviceFilterForm, SortUtil.parseSorter(bpDeviceFilterForm == null ? null : bpDeviceFilterForm.getSorter()));

        List<String> deviceIds = bpDeviceDtoPage.getRecords().stream().map(BpDeviceDto::getNumeration).collect(Collectors.toList());

        Collection<String> onlineDeviceIds = sessionManager.getOnlineDeviceIds(deviceIds);

        if (bpDeviceDtoPage.getRecords() != null && bpDeviceDtoPage.getRecords().size() > 0 && onlineDeviceIds != null && onlineDeviceIds.size() > 0) {
            for (BpDeviceDto bpDeviceDto : bpDeviceDtoPage.getRecords()) {
                for (String onlineDeviceId : onlineDeviceIds) {
                    if (bpDeviceDto.getNumeration().equals(onlineDeviceId)) {
                        bpDeviceDto.setState(1);
                        break;
                    }
                }
            }
        }

        return bpDeviceDtoPage;
    }

    @Override
    public List<BpDeviceDto> listOnlines(BpDeviceFilterForm bpDeviceFilterForm) {
        Page<BpDeviceDto> bpDeviceDtoPage = baseMapper.selectDeviceDtoPage(new Page<BpDeviceDto>(1l,
                1000l), bpDeviceFilterForm, SortUtil.parseSorter(bpDeviceFilterForm.getSorter()));


        List<String> deviceIds = bpDeviceDtoPage.getRecords().stream().map(BpDeviceDto::getNumeration).collect(Collectors.toList());

        Collection<String> onlineDeviceIds = sessionManager.getOnlineDeviceIds(deviceIds);
        List<String> lanyaBpDeviceIds = lanyaDeviceService.getOnlineBp().stream().map(BpInfo::getDeviceId).collect(Collectors.toList());
        onlineDeviceIds.addAll(lanyaBpDeviceIds);

        List<BpDeviceDto> onlines = new ArrayList<>();
        if (bpDeviceDtoPage.getRecords() != null && bpDeviceDtoPage.getRecords().size() > 0 && onlineDeviceIds != null && onlineDeviceIds.size() > 0) {
            for (BpDeviceDto bpDeviceDto : bpDeviceDtoPage.getRecords()) {
                for (String onlineDeviceId : onlineDeviceIds) {
                    if (bpDeviceDto.getNumeration().equals(onlineDeviceId)) {
                        XmbpDeviceSession session = (XmbpDeviceSession) sessionManager.getSession(onlineDeviceId);
                        if (session == null) {
                            log.info("设备：" + onlineDeviceId + "已离线");
                            break;
                        }
                        bpDeviceDto.setState(1);
                        bpDeviceDto.setLastPacketTime(session.getLastPacketTime());
                        bpDeviceDto.setLastSbp(session.getBpInfo().getSbp());
                        bpDeviceDto.setLastDbp(session.getBpInfo().getDbp());
                        onlines.add(bpDeviceDto);
                        break;
                    }
                }
            }
        }

        return onlines;
    }

    @Override
    @Transactional
    public void updateBpDevice(Integer id, BpDeviceForm bpDeviceForm) {
        Device device = new Device();
        device.setId(id);
        device.setNumeration(bpDeviceForm.getNumeration());

        deviceService.updateById(device);

        if (bpDeviceForm.getPatientId() != null) {
            device.setPatientId(bpDeviceForm.getPatientId());
            deviceService.bindDevice(bpDeviceForm.getPatientId(), bpDeviceForm.getNumeration());
        }

        try {
            BpDevice bpDevice = new BpDevice();
            bpDevice.setId(id);
            bpDevice.setMac(bpDeviceForm.getMac());

            updateById(bpDevice);
        } catch (Exception e) {
            e.printStackTrace();
            throw new MutilDeviceServiceException(ResponseEnum.ServerError);
        }
    }


}
